package com.raja.servingStation.common.util;

import org.apache.log4j.Logger;

import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


public class TimeUtil {
	private static Logger log = Logger.getLogger(TimeUtil.class);


	public static final String FORMAT_STR_SHORT = "yyyy-MM-dd";
	public static final String FORMAT_NUMBER_SHORT = "yyyyMMdd";
	public static final String FORMAT_STR_LONG = "yyyy-MM-dd HH:mm:ss";
	public static final String FORMAT_NUMBER_LONG = "yyyyMMddHHmmss";
	public static final DateFormat longDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static String year = "yyyy";
	private static String month = "MM";
	private static String day = "dd";
	public static SimpleDateFormat yearSDF = new SimpleDateFormat(year);
	public static SimpleDateFormat monthSDF = new SimpleDateFormat(month);
	public static SimpleDateFormat daySDF = new SimpleDateFormat(day);

	private static SimpleDateFormat df2 = new SimpleDateFormat(FORMAT_NUMBER_SHORT);
	public static SimpleDateFormat getDF2(){
		if(df2 == null){
			df2 = new SimpleDateFormat(FORMAT_NUMBER_SHORT);
		}
		return df2;
	}

	private static final ThreadLocal<SimpleDateFormat> SHORT_FORMAT = DateFormatUtil.threadLocalDateFormat("yyyyMMdd");

	/**
	 * 格式化时间（[yyyyMMddHHmmss]转换成[yyyy-MM-dd HH:mm:ss]）
	 * @return String
	 */
	public static String formatTime(long time) {
		String sTime = String.valueOf(time);
		Date date = stringToDate(sTime,TimeUtil.FORMAT_NUMBER_LONG);
		if(date!=null){
			return dateToString(date);
		}
		return null;
	}

	/**
	 * 格式化时间（[yyyy-MM-dd HH:mm:ss]转换成[yyyyMMddHHmmss]）
	 * @return Long
	 */
	public static Long formatTime(String time){
		try {
			SimpleDateFormat format = new SimpleDateFormat(TimeUtil.FORMAT_STR_LONG);
			Date date = format.parse(time);
			String str = dateToString(date, TimeUtil.FORMAT_NUMBER_LONG);
			return Long.parseLong(str);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 格式化时间（[yyyy-MM-dd]转换成[yyyyMMdd]）
	 * @return Long
	 */
	public static Integer formatDateTime(String time){
		try {
			SimpleDateFormat format = new SimpleDateFormat(TimeUtil.FORMAT_STR_SHORT);
			Date date = format.parse(time);
			String str = dateToString(date, TimeUtil.FORMAT_NUMBER_SHORT);
			return Integer.parseInt(str);
		} catch (ParseException e) {
			return null;
		}
	}

	/**
	 * 将Timestamp类型转换为String类型（默认格式）
	 * @return String
	 */
	public static String dateToString(Date date){
		return dateToString(date,TimeUtil.FORMAT_STR_LONG);
	}

	/**
	 * 将Timestamp类型转换为String类型（指定格式）
	 * @return String
	 */
	public static String dateToString(Date date, String format){
		if(date!=null){
			SimpleDateFormat FORMAT =  new SimpleDateFormat(format);
			return FORMAT.format(date);
		}
		return null;
	}

	/**
	 * 将String类型（默认格式）转换为Timestamp类型
	 * @return Date
	 */
	public static Date stringToDate(String str){
		return stringToDate(str,TimeUtil.FORMAT_STR_LONG);
	}

	/**
	 * 将long型(yyyyMMddHHmmss)时间转成Date对象
	 * @param time
	 * @return
	 */
	public static Date longToDate(long time){
		String str = formatTime(time);
		Date d = stringToDate(str);
		return d;
	}

	/**
	 * 将String类型（指定格式）转换为Timestamp类型
	 * @return Date
	 */
	public static Date stringToDate(String str, String format){
		if(str!=null && !"".equals(str)){
			SimpleDateFormat FORMAT =  new SimpleDateFormat(format);
			try {
				return FORMAT.parse(str);
			} catch (ParseException e) {
			}
		}
		return null;
	}

	/**
	 * 字符串转换为UTC的秒数（1970-01-01 00:00:00以后秒数）
	 * date 格式：yyyy-MM-dd HH:mm:ss
	 * @return long
	 */
	public static long StringToUTC(String date) {
		long result = 0;
		try {
			Date cdate = stringToDate(date);
			if (cdate != null) {
				Calendar cal = Calendar.getInstance();
				cal.setTime(cdate);
				result = cal.getTimeInMillis() / 1000;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 将UTC的秒数（1970-01-01 00:00:00以后秒数）转换为字符串（yyyy-MM-dd HH:mm:ss）
	 * @return String
	 */
	public static String UTCToString(long utcTime){
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(utcTime*1000);
		return dateToString(cal.getTime());
	}

	/**
	 * 将UTC的秒数（1970-01-01 00:00:00以后秒数）转换为字符串（按日期格式）
	 * @return String
	 */
	public static String UTCToString(long utcTime,String format){
		Calendar cal = Calendar.getInstance();
		cal.setTimeInMillis(utcTime*1000);
		return dateToString(cal.getTime(),format);
	}

	/**
	 * UTC时间(1970-01-01 00:00:00以后秒数) 转换为Date对象
	 * @param utcTime
	 * @param format
	 * @return
	 */
	public static Date UTCToDate(long utcTime,String format){
		String str = UTCToString(utcTime, format);
		Date d = stringToDate(str);
		return d;
	}

	public static Date UTCToDate(long utcTime){
		String str = UTCToString(utcTime);
		Date d = stringToDate(str);
		return d;
	}

	/**
	 * 将秒数转化为01:01:01格式
	 * @return String
	 */
	public static String formatSecond(int second) {
		if (second < 0) {
			return null;
		} else if (second == 0) {
			return "00:00:00";
		} else {
			int oneHour = 3600;
			int oneMinute = 60;
			String hours = second / oneHour < 10 ? "0" + second / oneHour
					: second / oneHour + "";
			String minutes = second % oneHour / oneMinute < 10 ? "0" + second
					% oneHour / oneMinute : second % oneHour / oneMinute + "";
			String seconds = second % oneHour % oneMinute < 10 ? "0" + second
					% oneHour % oneMinute : second % oneHour % oneMinute + "";
			StringBuffer sb = new StringBuffer();
			sb.append(hours).append(":").append(minutes).append(":").append(seconds);
			return sb.toString();
		}
	}
	/**
	 * 将秒数转化为01:01:01格式
	 * @return String
	 */
	public static String formatSecond(long second) {
		if (second < 0) {
			return null;
		} else if (second == 0) {
			return "00:00:00";
		} else {
			int oneHour = 3600;
			int oneMinute = 60;
			String hours = second / oneHour < 10 ? "0" + second / oneHour
					: second / oneHour + "";
			String minutes = second % oneHour / oneMinute < 10 ? "0" + second
					% oneHour / oneMinute : second % oneHour / oneMinute + "";
			String seconds = second % oneHour % oneMinute < 10 ? "0" + second
					% oneHour % oneMinute : second % oneHour % oneMinute + "";
			StringBuffer sb = new StringBuffer();
			sb.append(hours).append(":").append(minutes).append(":").append(seconds);
			return sb.toString();
		}
	}

	/**
	 * 将秒数转化为 01小时01分钟01秒 格式
	 * @param second
	 * @return
	 */
	public static String formatSecondExt(int second) {
		StringBuffer sb = new StringBuffer();
		int totalSec = second<0?0:second;

		int day = totalSec / (3600 * 24);
		totalSec = totalSec % (3600 * 24);
		int hour = totalSec / 3600;
		totalSec = totalSec % 3600;
		int min = totalSec / 60;
		totalSec = totalSec % 60;
		int sec = totalSec;

		if (day > 0) {
			sb.append(day).append("天");
		}

		if (hour > 0) {
			sb.append(hour).append("小时");
		}

		if (min > 0) {
			sb.append(min > 9 ? min : "0" + min).append("分钟");
		} else {
			sb.append("00").append("分钟");
		}
		if (sec > 0) {
			sb.append(sec > 9 ? sec : "0" + sec).append("秒");

		} else {
			sb.append("00").append("秒");
		}

		return sb.toString();
	}

	/**
	 * 将秒数转化为 xx天01小时01分钟01秒 格式
	 * @param second
	 * @return
	 */
	public static String formatSecondExt(long second) {
		StringBuffer sb = new StringBuffer();
		long totalSec = second<0?0:second;

		long day = totalSec/(24*3600);
		long hour = totalSec / 3600;

		totalSec = totalSec % 3600;
		long min = totalSec / 60;
		totalSec = totalSec % 60;
		long sec = totalSec;
		if (hour >= 24) {
			hour = hour % 24;
		}
		if(day > 0){
			sb.append(day).append("天");
		}
		if (hour > 0) sb.append(hour).append("小时");
		if (min > 0) {
			sb.append(min > 9?min:"0"+min).append("分钟");
		}else{
			sb.append("00").append("分钟");
		}
		if(sec > 0){
			sb.append(sec > 9?sec:"0"+sec).append("秒");

		}else{
			sb.append("00").append("秒");
		}

		return sb.toString();
	}

	/**
	 * 获取startTime之后second秒的时间
	 * @param startTime
	 * @param second
	 * @return String
	 */
	public static String getEndTime(String startTime,int second) {
		SimpleDateFormat FORMAT =  new SimpleDateFormat(TimeUtil.FORMAT_STR_LONG);
		String newtime=null;
		try {
			Long time= FORMAT.parse(startTime).getTime()+second*1000;
			newtime=FORMAT.format(time);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return newtime;
	}

	//是否第一个日期小于第二个日期（是否过期日期小于当前日期：若小于则过期）
	public static boolean isSmallDate(Date date, Integer d2){
		if(date!=null){
			Integer d1 = Integer.parseInt(getDF2().format(date));
			if(d1<d2) return true;
		}
		return false;
	}

	/**
	 * 判断srcDate是否小于destDate
	 * @param srcDate
	 * @param destDate
	 * @return 是：true，否：fale
	 */
	public static boolean isSmallDate(Date srcDate, Date destDate) {
		if (srcDate != null && destDate != null) {
			return srcDate.before(destDate);
		}
		return false;
	}

	//获取今天凌晨0点0分0秒的时间
	public static long getTodayTime(){
		Calendar cal = Calendar.getInstance();
		cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DAY_OF_MONTH),0,0,0);
		return cal.getTimeInMillis();
	}

	/**
	 * 时间格式转换为秒数
	 * @param date
	 * @return
	 */
	public static long dateToUTC(Date date) {
		if (date != null) {
			Calendar cal = Calendar.getInstance();
			cal.setTime(date);
			return cal.getTimeInMillis() / 1000;
		}
		return 0;
	}


	/**
	 * 根据类型返回时间长度
	 * @param startTime
	 * @param endTime
	 * @param type h:小时
	 * @return
	 */
	public static double getDateDiffByType(String startTime,String endTime,String type){
		double ret = 0d;
		DecimalFormat df = new DecimalFormat("0.00");
		try {
			Date start = longDateFormat.parse(startTime);
			Date end = longDateFormat.parse(endTime);
			float l = 0f;
			if (end.getTime() < start.getTime()) {
				l =start.getTime() - end.getTime();	//转换成秒
			}else{
				l =end.getTime() - start.getTime();	//转换成秒
			}
			if (type.equals("h")) {
				ret = new Double(df.format(l/(60*60*1000)).toString());
			}
			log.error(start.getTime()+"==>"+end.getTime()+"==>"+l+"==>"+ret);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	/**
	 * 获取两个日期的差值
	 */
	public static String getDateDiff(String startTime,String endTime){
		try {
			if (DataUtil.isNotEmpty(startTime) && DataUtil.isNotEmpty(endTime)) {
				Date start = longDateFormat.parse(startTime);
				Date end = longDateFormat.parse(endTime);
				long l = 0;
				if (end.getTime() < start.getTime()) {
					l =start.getTime() - end.getTime();	//转换成秒
				}else{
					l =end.getTime() - start.getTime();	//转换成秒
				}
				long day = l/(24*60*60*1000);
				long hour = (l/(60*60*1000)-day*24);
				long minute = ((l/(60*1000))-day*24*60-hour*60);
				long sec = (l/1000-day*24*60*60-hour*60*60-minute*60);
				if(day == 0l){
					if (hour == 0l) {
						return minute+"分"+sec+"秒";
					}else{
						return hour+"时"+minute+"分"+sec+"秒";
					}
				}else{
					return day+"天"+hour+"时"+minute+"分"+sec+"秒";
				}
			}else{
				return "-";
			}

		} catch (Exception e) {
			log.error(e);
		}
		return null;
	}

	/**
	 * 获取两个日期的差值
	 */
	public static String getDateDiffForDate(Date start,Date end){
		try {
			long l = 0;
			if (end.getTime() < start.getTime()) {
				l =start.getTime() - end.getTime();	//转换成秒
			}else{
				l =end.getTime() - start.getTime();	//转换成秒
			}
			long day = l/(24*60*60*1000);
			long hour = (l/(60*60*1000)-day*24);
			long minute = ((l/(60*1000))-day*24*60-hour*60);
			long sec = (l/1000-day*24*60*60-hour*60*60-minute*60);
			if(day == 0l){
				if (hour == 0l) {
					return minute+"分"+sec+"秒";
				}else{
					return hour+"时"+minute+"分"+sec+"秒";
				}
			}else{
				return day+"天"+hour+"时"+minute+"分"+sec+"秒";
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 格式化时间（[yyyyMMddHHmmss]转换成秒数）
	 * @return String
	 */
	public static long formatTimeToSec(long time) {
		String sTime = String.valueOf(time);
		Date date = stringToDate(sTime,TimeUtil.FORMAT_NUMBER_LONG);
		if(date!=null){
			return date.getTime();
		}
		return 0l;
	}

	/**
	 * 获取一周/一个月/一年后的日期
	 * @param type
	 * @return
	 */
	public static String getOverDateByType(String type,String formate){
		Calendar curr = Calendar.getInstance();
		if (type.equals("DAY")) {
			curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH)+7);
		}else if (type.equals("MONTH")) {
			curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)+1);
		}else if (type.equals("YEAR")) {
			curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)+1);
		}
		Date date = curr.getTime();
		String retDate =  dateToString(date, formate);
		return retDate;

	}

	/**
	 * 将1970到现在秒数转换成yyyy-MM-dd HH:mm:ss
	 * @param time
	 * @param format
	 * @return
	 */
	public static String secToTime(long time,String format){
		Date d = new Date();
		SimpleDateFormat df = new SimpleDateFormat(format);
		d.setTime(time);
		String s = df.format(d);
		return s;
	}

	// getDateBefore type类型
	public static final int DATE_BEFORE = 1; // 几天前
	public static final int DATE_AFTER = 2; // 几天后

	/**
	 * 获取day天前/后的时间
	 * @param d
	 * @param day
	 * @type type
	 * @return
	 */
	public static Date getDateBefore(Date d, int day, int type){
		Calendar now = Calendar.getInstance();
		now.setTime(d);
		if (type == 1) {	//几天前
			now.set(Calendar.DATE, now.get(Calendar.DATE)-day);
		}else if (type == 2) {	//几天后
			now.set(Calendar.DATE, now.get(Calendar.DATE)+day);
		}
		return now.getTime();
	}

	/**
	 * 比较两个时间是否大于/小于指定秒数
	 * @param st	开始时间
	 * @param et	结束时间
	 * @param compareTick	要比较的差值(单位秒)
	 * @param type	1:大于 2:小于
	 * @return type:1 return false:两个时间差值小于指定时间
	 * 				         true :两个时间差值大于等于指定时间
	 * 		   type:2 return false:两个时间差值大于指定时间
	 * 				         true :两个时间差值小于等于指定时间
	 */
	public static boolean checkDateDiff(Date st,Date et,long compareTick,int type){
		long stick = st.getTime();
		long etick = et.getTime();
//		System.out.println(etick+"====>"+stick+"===>"+(etick - stick));
		if (type == 1) {
			if (etick - stick > compareTick) {
				return true;
			}else{
				return false;
			}
		}else if (type == 1) {
			if (etick - stick < compareTick) {
				return true;
			}else{
				return false;
			}
		}
		return false;
	}

	/**
	 *获取当前的年、月、日
	 * @return String
	 */
	public static String getCurrentYear() {
		return yearSDF.format(new Date());
	}
	public static String getCurrentMonth() {
		return monthSDF.format(new Date());
	}
	public static String getCurrentDay() {
		return daySDF.format(new Date());
	}

	/**
	 * 获取一周/一个月/一年前的日期
	 * @param type
	 * @return
	 */
	public static String getBeforDateByType(String type,String formate){
		Calendar curr = Calendar.getInstance();
		if (type.equals("DAY")) {
			curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH)-7);
		}else if (type.equals("MONTH")) {
			curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)-1);
		}else if (type.equals("YEAR")) {
			curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)-1);
		}
		Date date = curr.getTime();
		String retDate =  dateToString(date, formate);
		return retDate;

	}

	//根据类型判断时间是否处于指定时间段内
	public static boolean isDateExistInTargetTimes(int type,Date d){
		Date now = new Date();
		Calendar curr = Calendar.getInstance();
		if (type == 1) {//一周以内
			//获取7天前的时间
			curr.set(Calendar.DAY_OF_MONTH, curr.get(Calendar.DAY_OF_MONTH)-7);
			Date d7 = curr.getTime();
			if ((d.getTime() >= d7.getTime()) && (d.getTime() <= now.getTime())) {
				return true;
			}else{
				return false;
			}
		}else if (type == 2) {//一月以内
			curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)-1);
			Date m = curr.getTime();
			if ((d.getTime() >= m.getTime()) && (d.getTime() <= now.getTime())) {
				return true;
			}else{
				return false;
			}
		}else if (type == 3) {//半年
			curr.set(Calendar.MONTH,curr.get(Calendar.MONTH)-6);
			Date hy = curr.getTime();
			if ((d.getTime() >= hy.getTime()) && (d.getTime() <= now.getTime())) {
				return true;
			}else{
				return false;
			}
		}else if (type == 4) {//一年
			curr.set(Calendar.YEAR,curr.get(Calendar.YEAR)-1);
			Date y = curr.getTime();
			if ((d.getTime() >= y.getTime()) && (d.getTime() <= now.getTime())) {
				return true;
			}else{
				return false;
			}
		}
		return false;
	}

	/**
	 * 将long型(yyyyMMddHHmmss)时间按照自定义格式转成字符串
	 * @param time
	 * @return
	 */
	public static String longToStr(long time,String format){
		String str = formatTime(time);
		Date d = stringToDate(str);
		String timeStr = dateToString(d, format);
		return timeStr;
	}

	/**
	 * 日期类型转换为yyyyMMdd
	 * @param date
	 * @return
	 */
	public static int date2Int(Date date) {
		SimpleDateFormat FORMAT = SHORT_FORMAT.get();
		return Integer.parseInt(FORMAT.format(date));
	}

	public static void main(String[] args) {
		long t1 = System.currentTimeMillis();
		System.out.println(t1);
	}
}
